package com.lgd.factoryattendance.Activity;

import androidx.appcompat.app.AppCompatActivity;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.provider.Settings;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.Spinner;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.lgd.factoryattendance.Bean.AssemblyGallery;
import com.lgd.factoryattendance.Bean.AssemblyManagement;

import com.lgd.factoryattendance.Bean.ProjectManagement;
import com.lgd.factoryattendance.Bean.ProjectSpinner;
import com.lgd.factoryattendance.Bean.ProjectType;
import com.lgd.factoryattendance.R;
import com.lgd.factoryattendance.Utils.ScreenUtils;
import com.lgd.factoryattendance.Utils.ToastUtils;
import com.lgd.factoryattendance.View.MyCustomImageLayout;
import com.lgd.factoryattendance.View.PhotoShowDialog;
import com.lgd.factoryattendance.adapter.GalleryListAdapter;
import com.lgd.factoryattendance.adapter.MyAdapter;
import com.lgd.factoryattendance.adapter.UnitInfoAdapter;
import com.lgd.factoryattendance.httpService.API;
import com.lgd.factoryattendance.httpService.httpPort.IResponse;
import com.lgd.factoryattendance.httpService.httpPort.IStringResponse;
import com.wdeo3601.pdfview.PDFView;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class UnitInfoActivity extends BaseActivity implements View.OnClickListener {
    ListView unitInfo_LV ,lv_gallery;
    Spinner projectUnit_SP, sp_projectType, sp_projectName;
    private ArrayList<ProjectSpinner> projectSpinners = null;
    List<String> unitNameList = new ArrayList<>(); //  部装名字
    List<String> estimatedHoursList = new ArrayList<>();   //  预计工时
    List<String> creationTimeList = new ArrayList<>();  // 创建时间
    List<String> actualHoursList = new ArrayList<>();    //  实际时间
    List<String> assemblyidList = new ArrayList<>();     // 部装 id
    List<List<String>> unitListItem = null;
//    Long assemblyid ;
    int type ; // 1 下拉框类型    2 部装详情
    MyCustomImageLayout mPhotoGridView;  //  多图展示
    ArrayList<String> imageList = new ArrayList<>();  //图片列表
    List<String> drawingnumberLiat = new ArrayList<>();
    List<String> drawingpathList = new ArrayList<>();
    List<List<String>> galleryListItem = null;
    LinearLayout layout_back;
    ImageView iv_img, iv_refresh;
    private static final String TAG = "UnitInfoActivity";
    private final List<ProjectSpinner> projectnameList = new ArrayList<>();  // 项目 列表
    String ANDROID_ID;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_unit_info);
        init();
    }

    @SuppressLint("HardwareIds")
    public void init(){
        ANDROID_ID = Settings.Secure.getString(getContentResolver(), Settings.Secure.ANDROID_ID);
        iv_refresh = findViewById(R.id.iv_refresh);
        iv_refresh.setOnClickListener(this);
        sp_projectType = findViewById(R.id.sp_projectType);
        iv_img = findViewById(R.id.iv_img);
        layout_back = findViewById(R.id.layout_back);
        layout_back.setOnClickListener(this);
        projectUnit_SP = findViewById(R.id.projectUnit_SP);
        unitInfo_LV = findViewById(R.id.unitInfo_LV);
        projectType();

    }
    // 重启 当前 activity 方法 --finish() 与 startActivity()----顺序不能错
    private void reStartActivity() {
        Intent intent = getIntent();
        overridePendingTransition(0, 0);
        intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
        finish();
        overridePendingTransition(0, 0);
        startActivity(intent);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.layout_back:
                finish();
                break;
            case R.id.iv_refresh:
                reStartActivity();
                break;
            default:
                break;
        }
    }
    // 获取 项目分类 数据
    public List<String> projectType_list = new ArrayList<>();
    public void projectType(){
        API.projectType(new IResponse() {
            @Override
            public void onSuccess(String response) throws IOException {
                UnitInfoActivity.this.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        JSONObject j = JSONObject.parseObject(response);
                        List<ProjectType> projectTypeList = new Gson().fromJson(j.getString("data"), new TypeToken<List<ProjectType>>(){}.getType());
                        Log.d(TAG, "-----项目类型----"+projectTypeList);
                        if (projectTypeList.size() > 0){
                            projectType_list.add("选择类型");
                            for (ProjectType type : projectTypeList) {
                                projectType_list.add(type.getTypename());
                            }
                        }
                        typeSpinner();
                    }
                });
            }
            @Override
            public void onFail(int statusCode) {
                Log.d(TAG, "onFail: -----刷新错误------:  "+statusCode);
            }
        });
    }

    ArrayAdapter<String> typeSpinner_adapter;
    //  类型 spinner 实例化
    public void typeSpinner(){
        typeSpinner_adapter = new ArrayAdapter<>(getApplicationContext(),R.layout.spinner_item,projectType_list);
        sp_projectType.setAdapter(typeSpinner_adapter);
        sp_projectType.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                Log.d(TAG, "----spinner选中类型----"+projectType_list.get(position));
                String str_spinner = projectType_list.get(position);
                projectnameList.clear();
                adapter = new MyAdapter(projectnameList, UnitInfoActivity.this);
                projectUnit_SP.setAdapter(adapter);
                if (str_spinner.equals("选择类型")) {
                    ToastUtils.warnShowLong(getApplicationContext(),"请选择项目类型！！！");
                    iv_img.setVisibility(View.VISIBLE);
                    unitInfo_LV.setVisibility(View.GONE);
                }else {
                    iv_img.setVisibility(View.GONE);
                    unitInfo_LV.setVisibility(View.VISIBLE);
                    ProjectType projectType = new ProjectType();
                    projectType.setTypename(projectType_list.get(position));
                    projectType.setSerialnumber(ANDROID_ID);
                    getStartProjectInfo(projectType);
                }
            }
            @Override
            public void onNothingSelected(AdapterView<?> parent) {}
        });
    }

    public void getStartProjectInfo(ProjectType projectType){
        API.getStartProjectInfo(projectType, new IStringResponse() {
            @Override
            public void onSuccess(String result) {
                UnitInfoActivity.this.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        JSONObject j = JSONObject.parseObject(result);
                        List<ProjectManagement> projectManagementList = new Gson().fromJson(j.getString("data"), new TypeToken<List<ProjectManagement>>(){}.getType());
                        System.out.println("----123456789------"+projectManagementList);
                        projectnameList.clear();
                        if (projectManagementList.size() > 0){
                            for (ProjectManagement p : projectManagementList) {
                                projectnameList.add(new ProjectSpinner(p.getProjectname(),
                                        p.getProductacode(),
                                        p.getProjectid(),
                                        p.getDeptid()));
                            }
                        }else {
                            ToastUtils.warnShowLong(getApplicationContext(),"当前设备下没有该类型的项目，请重新选择");
                        }
                        setProject(projectnameList);
                    }
                });
            }
            @Override
            public void onFail(int statusCode) {}
        });
    }
    MyAdapter adapter;
    public void setProject(List<ProjectSpinner> projectnameList){
        adapter = new MyAdapter(projectnameList, UnitInfoActivity.this);
        projectUnit_SP.setAdapter(adapter);
        projectUnit_SP.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @SuppressLint("SetTextI18n")
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

                Log.d(TAG, "---项目名称---"+projectnameList.get(position).getProjectName()+
                        "--项目code---"+projectnameList.get(position).getProjectACode()+
                        "---项目 id---"+projectnameList.get(position).getProjectId()+
                        "---部门id--"+projectnameList.get(position).getDeptId());
                type = 1;
                clearUnitList();
                AssemblyManagement ass = new AssemblyManagement();
//                ass.setProductacode(projectnameList.get(position).getProjectACode());
                ass.setProjectid(projectnameList.get(position).getProjectId());
                findAssByAcode(ass);
            }
            @Override
            public void onNothingSelected(AdapterView<?> parent) { }
        });
    }

///  部装信息
    public void findAssByAcode(AssemblyManagement a){
        API.findAssByAcode(a, new IStringResponse() {
            @Override
            public void onSuccess(String result) {
                UnitInfoActivity.this.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        JSONObject j = JSONObject.parseObject(result);
                        List<AssemblyManagement> assList = new Gson().fromJson(j.getString("data"), new TypeToken<List<AssemblyManagement>>(){}.getType() );
                        System.out.println("------  部装 信息-------"+assList);
                        if (assList != null && !assList.isEmpty()){
                            iv_img.setVisibility(View.GONE);
                            unitInfo_LV.setVisibility(View.VISIBLE);
                            switch (type){
                                case 1:
                                    for (int i = 0; i < assList.size(); i++) {
                                        unitNameList.add(assList.get(i).getAssemblyname());
                                        estimatedHoursList.add(assList.get(i).getEstimatedworkinghours());
                                        creationTimeList.add(assList.get(i).getCreationtime());
                                        actualHoursList.add(assList.get(i).getRealityworkinghours());
                                        assemblyidList.add(String.valueOf(assList.get(i).getAssemblyid()));
                                    }
                                    unitInfoListview();
                                    break;
                                case 2:
                                    imageList.clear();
                                    System.out.println("---- 部装信息--"+assList+"----size:---"+assList.size());
                                    assProjectName_TV.setText(assList.get(0).getProjectName());
                                    assAcode_TV.setText(assList.get(0).getProductacode());
                                    assName_TV.setText(assList.get(0).getAssemblyname());
                                    assforecastTime_TV.setText(assList.get(0).getEstimatedworkinghours());
                                    assActualTime_TV.setText(assList.get(0).getRealityworkinghours());
//                                    if (assList.get(0).getAssemblydescribe().equals("")){
//                                        assRemark_TV.setText("暂无备注");
//                                    }else {
                                        assRemark_TV.setText(assList.get(0).getAssemblydescribe());
//                                    }
//                                    if (assList.get(0).getOverduereason().equals("")){
//                                        assReason_TV.setText("暂无原因");
//                                    }else {
                                        assReason_TV.setText(assList.get(0).getOverduereason());
//                                    }

                                    assTime_TV.setText(assList.get(0).getCreationtime());
                                    String s = assList.get(0).getProcessPic();
                                    if (s != null && !s.equals("")){
                                        String[] strings =s.split(",");
                                        for (String url : strings){
                                            url = url.trim();
                                            imageList.add(url);
                                        }
                                        System.out.println(imageList+"----tuuuuuuu-----");
                                        //设置数据
                                        mPhotoGridView.setUrlListData(imageList);
                                    }
                                    //  根据 processesId  找到部装下 图库
                                    AssemblyGallery a = new AssemblyGallery();
                                    a.setProductionprocessesid(assList.get(0).getProcessesId());
                                    getGallery(a);
                                    break;
                            }

                        }else {
                            iv_img.setVisibility(View.VISIBLE);
                            unitInfo_LV.setVisibility(View.GONE);
                        }

                    }
                });
            }
            @Override
            public void onFail(int statusCode) {}
        });
    }
    PopupWindow assemblyInfo_pop;
    View assemblyInfo_view;
    //  部装信息列表
    public void assemblyInfoPop(){
        assemblyInfo_view = getLayoutInflater().inflate(R.layout.assembly_info_pop,null);
        int width = ScreenUtils.getWidth(getApplicationContext());
        int height = ScreenUtils.getRealHeight(getApplicationContext());
        assemblyInfo_pop = new PopupWindow
                (assemblyInfo_view, width * 9/10, height * 8/10);
        assemblyInfo_pop.setTouchable(true);
        assemblyInfo_pop.setFocusable(true);
        assemblyInfo_pop.setOutsideTouchable(true);
        assemblyInfo_pop.showAtLocation(UnitInfoActivity.this.getWindow().getDecorView(), Gravity.CENTER,0,0);
        initView();
    }
    TextView assProjectName_TV,assAcode_TV,assName_TV,assforecastTime_TV,assActualTime_TV,assRemark_TV,assReason_TV,assTime_TV;
    public void initView(){
        lv_gallery = assemblyInfo_view.findViewById(R.id.lv_gallery);
        mPhotoGridView = assemblyInfo_view.findViewById(R.id.image_layout);
        assProjectName_TV = assemblyInfo_view.findViewById(R.id.assProjectName_TV);
        assAcode_TV = assemblyInfo_view.findViewById(R.id.assAcode_TV);
        assName_TV = assemblyInfo_view.findViewById(R.id.assName_TV);
        assforecastTime_TV = assemblyInfo_view.findViewById(R.id.assforecastTime_TV);
        assActualTime_TV = assemblyInfo_view.findViewById(R.id.assActualTime_TV);
        assRemark_TV = assemblyInfo_view.findViewById(R.id.assRemark_TV);
        assReason_TV = assemblyInfo_view.findViewById(R.id.assReason_TV);
        assTime_TV = assemblyInfo_view.findViewById(R.id.assTime_TV);
        ImageView iv_close = assemblyInfo_view.findViewById(R.id.iv_close);
        iv_close.setOnClickListener(new View.OnClickListener() {  // 关闭
            @Override
            public void onClick(View v) {
                assemblyInfo_pop.dismiss();
            }
        });
        //  图片点击事件
        mPhotoGridView.setOnImageClickListener((i, imageGroupList, urlList) -> {
            //图片下标+1
            int index = (int)i.getTag(R.id.tag_glide) + 1;
            //单个图片的点击事件
            System.out.println("------ 点击了图片-------"+index);
            PhotoShowDialog photoShowDialog = new PhotoShowDialog(UnitInfoActivity.this,urlList,index);
            photoShowDialog.show();
        });
    }

    //  图库 信息
    public void getGallery(AssemblyGallery a){
        API.getGallery(a, new IStringResponse() {
            @Override
            public void onSuccess(String result) {
                UnitInfoActivity.this.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        JSONObject j = JSON.parseObject(result);
                        List<AssemblyGallery> assemblyGalleryList = new Gson().fromJson(j.getString("data"), new TypeToken<List<AssemblyGallery>>(){}.getType() );
                        if (assemblyGalleryList != null){
                            for (AssemblyGallery a : assemblyGalleryList) {
                                drawingnumberLiat.add(a.getDrawingnumber());
                                drawingpathList.add(a.getDrawingpath());
                            }
                        }
                        galleryInfoListview();
                    }
                });
            }
            @Override
            public void onFail(int statusCode) {}
        });
    }
    //  项目下拉框
    public void findProjectName(ProjectManagement p){
        API.findProjectName(p, new IStringResponse() {
            @Override
            public void onSuccess(String result) {
                UnitInfoActivity.this.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        JSONObject j = JSONObject.parseObject(result);
                        List<ProjectManagement> projectManagements = new Gson().fromJson(j.getString("data"), new TypeToken<List<ProjectManagement>>(){}.getType() );
                        projectSpinners = new ArrayList<>();
                        if (projectManagements != null){
                            for (ProjectManagement p : projectManagements) {
                                projectSpinners.add(new ProjectSpinner(p.getProductacode(),
                                        p.getProjectname()));
                            }
                        }else {
                            ToastUtils.warnShowLong(UnitInfoActivity.this,"网络不稳定请重试！");
                        }
                    }
                });
            }
            @Override
            public void onFail(int statusCode) {}
        });
    }
    // 清除 部装列表
    public void clearUnitList(){
        if (unitListItem != null){
            unitListItem.clear();
            unitNameList.clear();
            estimatedHoursList.clear();
            creationTimeList.clear();
            actualHoursList.clear();
            assemblyidList.clear();
        }
    }
    // 清除图号 列表
    public void clearGalleryList (){
        if (galleryListItem != null){
            drawingnumberLiat.clear();
            drawingpathList.clear();
            galleryListItem.clear();
        }
    }
    //  图号自定义 listview 数据添加
    public void galleryInfoListview(){
        galleryListItem = new ArrayList<>();
        for (int i = 0; i < drawingnumberLiat.size(); i++) {
            List<String> galleryShowItem = new ArrayList<>();
            galleryShowItem.add(drawingnumberLiat.get(i));
            galleryShowItem.add(drawingpathList.get(i));
            galleryListItem.add(galleryShowItem);
        }
        GalleryListAdapter galleryListAdapter = new GalleryListAdapter(UnitInfoActivity.this,galleryListItem);
        lv_gallery.setAdapter(galleryListAdapter);
        lv_gallery.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                System.out.println(galleryListItem.get(position).get(1)+"-------  图号地址 ------------");
                String path = galleryListItem.get(position).get(1);
                showPdfInDialog(path);
            }
        });
    }


    //  列表实例化
    public void unitInfoListview(){
        unitListItem = new ArrayList<>();
        for (int i = 0; i < unitNameList.size(); i++) {
            List<String> unitShowItem = new ArrayList<>();
            unitShowItem.add(unitNameList.get(i));
            unitShowItem.add(estimatedHoursList.get(i));
            unitShowItem.add(creationTimeList.get(i));
            unitShowItem.add(actualHoursList.get(i));
            unitShowItem.add(assemblyidList.get(i));
            unitListItem.add(unitShowItem);
        }
        if (unitListItem ==null || unitListItem.isEmpty()){
            iv_img.setVisibility(View.VISIBLE);
            unitInfo_LV.setVisibility(View.GONE);
        }else {
            iv_img.setVisibility(View.GONE);
            unitInfo_LV.setVisibility(View.VISIBLE);
            UnitInfoAdapter unitInfoAdapter = new UnitInfoAdapter(UnitInfoActivity.this,unitListItem);
            unitInfo_LV.setAdapter(unitInfoAdapter);
            unitInfo_LV.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    type = 2;
                    clearGalleryList();  // 清除列表信息
                    //  部装 信息弹窗
                    assemblyInfoPop();
                    new Handler().postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            AssemblyManagement ass = new AssemblyManagement();
                            ass.setAssemblyid(Long.valueOf(unitListItem.get(position).get(4)));
                            findAssByAcode(ass);
                        }
                    },400);
                    setAlpha(0.4f);
                    assemblyInfo_pop.setOnDismissListener(new PopupWindow.OnDismissListener() {
                        @Override
                        public void onDismiss() {
                            setAlpha(1.0f);
                        }
                    });
                }
            });
        }

    }
    Dialog dialog;
    // dialog 查看 PDF
    private void showPdfInDialog(String pdfPath) {
        dialog = new Dialog(UnitInfoActivity.this);
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        dialog.setContentView(R.layout.dialog_pdf_viewer);
        dialog.getWindow().setBackgroundDrawableResource(android.R.color.transparent); // 设置Dialog背景透明
        dialog.getWindow().setLayout(WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.WRAP_CONTENT); // 设置Dialog大小
        dialog.getWindow().setGravity(Gravity.CENTER);
        dialog.show();
        //  PDF 控件设置
        PDFView pdfView = dialog.findViewById(R.id.pdfView);
        pdfView.isCanZoom(true);
        pdfView.setMaxScale(10f);
        pdfView.showPdfFromUrl(pdfPath);

        LinearLayout layout_back = dialog.findViewById(R.id.layout_back);
        layout_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });

    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (dialog != null){
            dialog.dismiss();
        }
        clearGalleryList();
        clearUnitList();
    }
    //    遮罩层
    private void setAlpha(float f) {
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.alpha = f;
        getWindow().setAttributes(lp);
    }
}